package net.wanho.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.SneakyThrows;
import net.wanho.entity.User;
import net.wanho.vo.AjaxResult;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2024-01-10 10:26
 * Description：<描述>
 */
@RestController
public class EasyPOIController {

    @SneakyThrows
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        List<User> list = new ArrayList<>();
        list.add(new User(1,"aa","123",18,"aa@qq.com", LocalDateTime.now(),0));
        list.add(new User(2,"bb","123",28,"bb@qq.com", LocalDateTime.now(),1));
        list.add(new User(3,"cc","678",58,"cc@qq.com", LocalDateTime.now(),1));
        list.add(new User(4,"dd","123",19,"dd@qq.com", LocalDateTime.now(),0));

        ExportParams params = new ExportParams("用户信息表","用户表");
        Workbook workbook = ExcelExportUtil.exportExcel(params, User.class, list);

        // 设置响应内容类型
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        // 设置处理方式，并指定下载文件名
        response.setHeader("Content-Disposition","attachment;filename="+new String("用户信息表.xls".getBytes("utf-8"),"iso8859-1"));
        // 将excel写入响应流
        workbook.write(response.getOutputStream());
    }

    @SneakyThrows
    @PostMapping("/import")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file){
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);

        List<User> list = ExcelImportUtil.importExcel(file.getInputStream(), User.class, params);
        list.forEach(System.out::println);

        return AjaxResult.success();
    }

}
